package com.topdt.jbpm.web.struts.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.util.ObjectUtils;
import com.thx.common.web.ActionResult;
import com.thx.log.LogUtil;
import com.topdt.jbpm.dto.View;
import com.topdt.jbpm.form.FormMenuDefin;
import com.topdt.jbpm.model.Activity;
import com.topdt.jbpm.model.AppAuthority;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Control;
import com.topdt.jbpm.model.Field;
import com.topdt.jbpm.service.ActivityService;
import com.topdt.jbpm.service.ApplicationService;
import com.topdt.jbpm.service.ControlService;
import com.topdt.jbpm.utils.ModuleConstant;

/**
 *
* @author 资丽
* @ClassName: AuthorityAction
* @Description:流程环节的操作权限，流程环节的提醒和流程环节的增加意见方式
* @date 2015年4月16日 下午3:33:32
 */
@Namespace("/workflow")
@Action(value = "authority",
		results = {
		@Result(name = "operate", location = "/workflow/app/flow-operate.jsp"),
		@Result(name = "opinion", location = "/pages/workflow/authority/flowOpinion.jsp"),
		@Result(name = "remind", location = "/pages/workflow/authority/flowRemind.jsp"),
		@Result(name = "configOpinion", location = "/pages/workflow/authority/configFlowOpinion.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" })
		}
)
@Controller
@Scope("prototype")
public class AuthorityAction extends CurdAction<AppAuthority> {

	/**
	 *
	 */
	private static final long serialVersionUID = 2341520256619522360L;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private ControlService controlService;

	private String appId;
	private List<Activity> listActivity;
	private List<String> listS;
	private List<Control> listControl;
	private List<View> listView;
	private Map<String,String> mapView;
	private String[] options = {"已阅","已办","同意","不同意"};
	private String functionControls;

	private List<Field> listFields;
	private String opinions;
	
	private View dataView;
    /**
     *
    * @Description:流程操作权限列表
     */
	public String toFlowOperate() throws Exception {
		logger.debug("<进入>:toFlowOperate方法   得到流程操作权限列表");
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		String flowId = application.getFlowId();
		String flowKey = application.getFlowKey();
		// 通过flowId,flowKey获取活动集合
		listActivity = activityService.getActivityByFlow(flowId, flowKey);
		// 通过formId获取操作集合
		String[][] menus = FormMenuDefin.getMenuItems(application.getAppAttr());
		listS = new ArrayList<String>();
		for (int i = 0; i < menus.length; i++) {
			String[] menu = menus[i];
			if(StringUtils.isNotBlank(menu[0])) {
				listS.add(menu[1]);
			}
		}
		// 获取实体
		Object[] objs = new Object[] { appId, flowId, formId };
		listControl = controlService.findControlByObjects(objs);
		listView = new ArrayList<View>();

		if (listControl != null) {
			for (int i = 0; i < listControl.size(); i++) {
				View view = new View();
				view.setName(listControl.get(i).getActivityName());
				if (listControl.get(i).getFunctionControl() != null) {
					String functionControl = listControl.get(i).getFunctionControl();
					int funTrolLen = functionControl.length();
					// 没有进行表单转公文或没有进行公文转表单的情况
					if (funTrolLen == listS.size()) {
						view.setCheckStr(functionControl);
					}
					// 表单转公文的情况
					if (funTrolLen < listS.size()) {
						String zeros = "";
						for (int k = 0; k < (listS.size() - functionControl.length()); k++) {
							zeros += 0;
						}
						view.setCheckStr(functionControl + zeros);
					}
					// 公文转表单的情况
					if (funTrolLen > listS.size()) {
						int difValue = functionControl.length() - listS.size();
						String newFunControl = functionControl.substring(0,
								functionControl.length() - difValue);
						view.setCheckStr(newFunControl);
					}
				} else {
					String funControl = "";
					for (int j = 0; j < listS.size(); j++) {
						if (j == 0 || j == 1) {
							funControl += "1";
						} else {
							funControl += "0";
						}
					}
					view.setCheckStr(funControl);
				}
				listView.add(view);
			}
		}else{
		  for (int i = 0; i < listActivity.size(); i++) {
            View view = new View();
            view.setName(listActivity.get(i).getActivityName());
            String funControl = "";
            for (int j = 0; j < listS.size(); j++) {
                if (j == 0 || j == 1) {
                    funControl += "1";
                } else {
                    funControl += "0";
                }
            }
            view.setCheckStr(funControl);
            listView.add(view);
		  }
		}
		return "operate";
	}
	/**
	 *
	* @Description:流程提醒权限列表
	 */
	public String toFlowRemind(){
		logger.debug("<进入>:toFlowRemind方法   得到流程提醒权限列表");
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		String flowId = application.getFlowId();
		String flowKey = application.getFlowKey();
		//通过flowId,flowKey获取活动集合
		listActivity = activityService.getActivityByFlow(flowId,flowKey);
		//通过formId获取操作集合
		String[][] s = FormMenuDefin.getRemindmenuitems();
		listS = new ArrayList<String>();
		for(int i = 0 ; i<s.length; i++){
			String s1 = s[i][1];
				listS.add(s1);
		}
		//获取实体
		Object[] objs = new Object[]{appId,flowId,formId};
		listControl = controlService.findControlByObjects(objs);
		listView = new ArrayList<View>();
		if(listControl!=null){
			for(int i = 0; i<listControl.size(); i++){
				View view = new View();
				view.setName(listControl.get(i).getActivityName());
				if(listControl.get(i).getRemindControl()!=null){
					String remindControl = listControl.get(i).getRemindControl();
						view.setCheckStr(remindControl);
				}else{
					String remindControl = "";
					//edit 2014-11-19  默认下一步骤提醒方式全开启
					for(int j=0; j<listS.size(); j++){
						if(j==0){
							remindControl += "10";//去掉下一步骤提醒方式短信默认开启wangxufeng 2014-12-25
						}else{
							remindControl += "00";
						}
					}
					view.setCheckStr(remindControl);
				}
				listView.add(view);
			}
		}
		return "remind";
	}
	/**
	 *
	* @Description:流程环节意见方式列表
	 */
	public String toFlowOpinion(){
		logger.debug("<进入>:toFlowOpinion方法   得到环节意见方式列表");
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		String flowId = application.getFlowId();
		String flowKey = application.getFlowKey();
		//通过flowId,flowKey获取活动集合
		listActivity = activityService.getActivityByFlow(flowId,flowKey);
		//通过formId获取操作集合
		String[][] s = FormMenuDefin.getOptionMenuItems();
		listS = new ArrayList<String>();
		for(int i = 0 ; i<s.length; i++){
			String s1 = s[i][1];
				listS.add(s1);
		}
		//获取实体
		Object[] objs = new Object[]{appId,flowId,formId};
		listControl = controlService.findControlByObjects(objs);
		mapView = new HashMap<String, String>();
		if(listControl!=null){
			for(int i = 0; i<listControl.size(); i++){
				String defaultOption = "";
				String functionControl = listControl.get(i).getFunctionControl();
				//看是否有签署意见的权限
				if(StringUtils.isNotBlank(functionControl)){
					String option = functionControl.substring(3, 4);
					if(option.equals("1")){
						if(StringUtils.isNotBlank(listControl.get(i).getDefaultOption())){
							defaultOption = listControl.get(i).getDefaultOption();
						}
					}else{
						defaultOption = "none";
					}
				}
				mapView.put(listControl.get(i).getActivityName(),defaultOption);
			}
		}
		return "opinion";
	}


	/**
	 *  @Description    : 配置流程意见
	 *  @return
	 *  @return         : String
	 *  @version        : v1.00
	 */
	public String toConfigFlowOpinion(){
		logger.debug("<进入>:toConfigFlowOpinion方法   配置流程意见");
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		String flowId = application.getFlowId();
//		String flowKey = application.getFlowKey();
		// 通过flowId,flowKey获取活动集合
//		listActivity = activityService.getActivityByFlow(flowId, flowKey);

		//获取实体
		Object[] objs = new Object[]{appId,flowId,formId};
		listControl = controlService.findControlByObjects(objs);

		String className = application.getAppForm().getFormJava();
		Object obj = ObjectUtils.getInstance(className+"Opinion");
		java.lang.reflect.Field [] fields = obj.getClass().getDeclaredFields();
		Field f = null;
		listFields = new ArrayList<Field>();
		for(java.lang.reflect.Field field:fields){
			field.setAccessible(true);//设置访问权限
		    if(field.getName().contains("_name")){
		    	f = new Field();
		    	field.setAccessible(true);
		    	if(field.getType().getName().equals(java.lang.String.class.getName())){
		    		try {
		    			f.setFieldName(field.getName().split("_")[0]);
						f.setFieldText(field.get(obj).toString());
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
		    		listFields.add(f);
		    	}
		    }
		  }
		return "configOpinion";
	}

	/**
	 *
	* @Description:保存流程环节的操作权限
	 */
	public String saveOperateAuth() {
		logger.debug("<进入>:saveOperateAuth方法   保存流程环节的操作权限");
		try {
			Application application = applicationService.get(appId);

			String formId = application.getForm().getFormId();
			String flowId = application.getFlowId();
			String comId = AppContext.getCurrentComId();
			
			String[][] menus = FormMenuDefin.getMenuItems(application.getAppAttr());
			String[] controlNames = dataView.getName().split(",");
			String activityName = "";
			Control control = null;
			for(int i = 0; i<controlNames.length; i++){
			  activityName = controlNames[i].trim();
			  
			  control = new Control();
			  control.setCompanyId(comId);
			  control.setAppId(appId);
			  control.setFormId(formId);
			  control.setFlowId(flowId);
			  control.setActivityName(activityName);
			  
			  //组装操作权限设置开始
				char[] fuc = new char[menus.length];
				for(int k=0;k<fuc.length;k++){
				  fuc[k]='0';
				}
				String[] checkStr = dataView.getCheck().get(i).split(",");
				for(String checkValue:checkStr){
				  fuc[Integer.parseInt(checkValue.trim())-1]='1';
				}
				String functionControl = String.valueOf(fuc);
				//组装操作权限设置结束
				Object[] objs = new Object[]{appId,flowId,activityName,formId};
				Control controldb = controlService.getControlByObjects(objs);
				if(controldb!=null){
				  controldb.setFunctionControl(functionControl);
				  controlService.save(controldb);
				}else{
				  control.setFunctionControl(functionControl);
				  controlService.save(control);
				}
			}
			//--如果应用可用，作个标志
		    application.setIsComplete(applicationService.judgeApp(appId));
			applicationService.save(application);
			setResult(ActionResult.SUCCESS, "保存成功!");
			LogUtil.log(ModuleConstant.FLOW_OPERATE_AUTH, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "保存流程环节操作权限");
		} catch (Exception e) {
			setResult(ActionResult.FAIL, "保存失败！");
			logger.error("<错误>:保存流程环节的操作权限失败",e);
		}
		return JSON;
	}
	/**
	 *
	* @Description:保存流程环节的提醒方式
	 */
    public String saveRemindAuth(){
    	logger.debug("<进入>:saveRemindAuth方法   保存流程环节的提醒方式");
    		try {
				Application application = applicationService.get(appId);
				String formId = application.getForm().getFormId();
				String flowId = application.getFlowId();
				String[] s = functionControls.split(";");
				String activityName = "";
				for(int i = 0; i<s.length; i++){
					String remindControl = "";
					String[] s1 = s[i].split(",");
					activityName = s1[0];
					for(int j = 1; j<s1.length; j++){
						remindControl += s1[j];
					}
					Object[] objs = new Object[]{appId,flowId,activityName,formId};
					Control control = controlService.getControlByObjects(objs);
					if(control!=null){
						control.setControlId(control.getControlId());
						control.setRemindControl(remindControl);
						controlService.saveOrUpdate(control);
					}
				}
				setResult(ActionResult.SUCCESS, "保存成功!");
				LogUtil.log(ModuleConstant.FLOW_REMIND_WAY, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "保存流程环节的提醒方式");
			} catch (Exception e) {
				setResult(ActionResult.FAIL, "保存失败！");
				logger.error("<错误>:保存流程环节的提醒方式失败",e);
			}
    	    return JSON;
    }
    /**
     *
    * @Description:保存意见方式
     */
    public String saveOpinionAuth(){
    	logger.debug("<进入>:saveOpinionAuth方法   保存意见方式");
    	try {
			Application application = applicationService.get(appId);
			String formId = application.getForm().getFormId();
			String flowId = application.getFlowId();
			String[] s = functionControls.split(";");
			String activityName = "";
			for(int i = 0; i<s.length; i++){
				String defaultOption = "";
				String[] s1 = s[i].split(",");
				activityName = s1[0];
				if(s1.length>1){
					if(!"0".equals(s1[1])){
						defaultOption += s1[1];
					}
					Object[] objs = new Object[]{appId,flowId,activityName,formId};
					Control control = controlService.getControlByObjects(objs);
					if(control!=null){
						control.setControlId(control.getControlId());
						control.setDefaultOption(defaultOption);
						controlService.saveOrUpdate(control);
					}
				}
			}
			setResult(ActionResult.SUCCESS, "保存成功!");
			LogUtil.log(ModuleConstant.FLOW_OPINION_WAY, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "保存流程环节的意见方式");
		} catch (Exception e) {
			setResult(ActionResult.FAIL, "保存失败！");
			logger.error("<错误>:保存意见方式失败",e);
		}
    	return JSON;
    }


    /**
     *  @Description    : 保存配置流程环节意见
     *  @return
     *  @return         : String
     *  @version        : v1.00
     */
    public String saveConfigOpinion(){
    	logger.debug("<进入>:saveConfigOpinion方法   保存配置流程环节意见");
    	try {
			Application application = applicationService.get(appId);
			String formId = application.getForm().getFormId();
			String flowId = application.getFlowId();
			String[] s = opinions.split(";");

			String activityName = "";
			for(int i = 0; i<s.length; i++){
				String[] s1 = s[i].split(",");
				activityName = s1[0];
				if(s1.length > 0){
					Object[] objs = new Object[]{appId,flowId,activityName,formId};
					Control control = controlService.getControlByObjects(objs);
					if(control!=null){
						//fengjinshou 20160216 解决设置不需要填写意见时不能更新的bug
						if(s1.length>1){
							control.setOpinionName(s1[1]);
						}else{
							control.setOpinionName(null);
						}
						controlService.saveOrUpdate(control);
					}
				}
			}
			setResult(ActionResult.SUCCESS, "保存成功!");
		} catch (Exception e) {
			setResult(ActionResult.FAIL, "保存失败！");
			logger.error("<错误>:保存配置流程环节意见失败",e);
		}
    	return JSON;
    }

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public List<Activity> getListActivity() {
		return listActivity;
	}

	public void setListActivity(List<Activity> listActivity) {
		this.listActivity = listActivity;
	}

	public List<String> getListS() {
		return listS;
	}

	public void setListS(List<String> listS) {
		this.listS = listS;
	}

	public List<Control> getListControl() {
		return listControl;
	}

	public void setListControl(List<Control> listControl) {
		this.listControl = listControl;
	}

	public List<View> getListView() {
		return listView;
	}

	public void setListView(List<View> listView) {
		this.listView = listView;
	}

	public String getFunctionControls() {
		return functionControls;
	}

	public void setFunctionControls(String functionControls) {
		this.functionControls = functionControls;
	}
	public Map<String, String> getMapView() {
		return mapView;
	}
	public void setMapView(Map<String, String> mapView) {
		this.mapView = mapView;
	}
	public String[] getOptions() {
		return options;
	}
	public void setOptions(String[] options) {
		this.options = options;
	}
	public List<Field> getListFields() {
		return listFields;
	}
	public void setListFields(List<Field> listFields) {
		this.listFields = listFields;
	}
	public String getOpinions() {
		return opinions;
	}
	public void setOpinions(String opinions) {
		this.opinions = opinions;
	}
  public View getDataView() {
    return dataView;
  }
  public void setDataView(View dataView) {
    this.dataView = dataView;
  }

}
